package com.sibu.yx.promotion.web.support.model;

import java.util.List;

import com.sibu.yx.promotion.common.vo.UserToken;
import com.sibu.yx.promotion.service.support.util.JwtTokenUtil;
import com.sibu.yx.promotion.web.support.filter.UidToken;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;


/**
 * @author     ：yuwenbo
 * @date       ：Created in 2019/4/17 18:01
 * @description： 通过token验证登陆的
 */
public class TokenShiroRealm extends AuthorizingRealm {


    @Override
    public boolean supports(AuthenticationToken token) {
        if(token instanceof UidToken){
            return true;
        }
        return false;
    }


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //通过用户获取用户权限
        List<String> principalsList = principals.asList();
        //通过principals获取角色与权限
        SimpleAuthorizationInfo authorizationInfo=new SimpleAuthorizationInfo();
        //authorizationInfo.addRoles(Arrays.asList("admin","service"));
       // authorizationInfo.addStringPermissions(Arrays.asList("update:add","user:delete","pay:money"));
        //authorizationInfo.addObjectPermission(new BitPermission(5));//添加可读可修改
        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        UidToken uid=(UidToken) authenticationToken;

        UserToken userToken= JwtTokenUtil.getUserFromToken(uid.getToken());


        if (userToken ==null) {
            throw new UnknownAccountException("登录信息失效,请重新登录");
        }

        return new SimpleAuthenticationInfo(userToken.getUserId(), userToken.getUserId(), userToken.getUserName());
    }
}
